//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================


//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using LitwareHR.PrivateApp.Presenters.ConfigCusto.Process;
using LitwareHR.Portfolio.Gateways;
using System.Collections.Generic;
using LitwareHR.PrivateApp.WebUX.Properties;

public partial class ConfigCusto_Process_EditWorkflow : BasePage, IEditWorkflowView
{
    private EditWorkflowPresenter _presenter;

    protected override void OnInitComplete(EventArgs e)
    {
        base.OnInitComplete(e);
        _presenter = new EditWorkflowPresenter(this);
    }

    public List<WorkflowStep> Steps
    {
        get
        {
            List<WorkflowStep> list = ViewState["Steps"] as List<WorkflowStep>;
            if (list == null)
            {
                list = new List<WorkflowStep>();
                ViewState["Steps"] = list;
            }

            return list;
        }
        set
        {
            ViewState["Steps"] = value;
        }
    }

    public string ProcessName
    {
        get
        {
            return ProcessNameTextBox.Text;
        }

        set
        {
            ProcessNameTextBox.Text = value;
            SetProcessNameEnabled(value);
        }
    }

    private void SetProcessNameEnabled(string name)
    {
        if (String.Compare(name, "Short Workflow", StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(name, "Long Workflow", StringComparison.OrdinalIgnoreCase) == 0)
        {
            this.ProcessNameTextBox.Enabled = false;
        }
        else
        {
            this.ProcessNameTextBox.Enabled = true;
        }
    }

    public Guid ProcessId
    {
        get
        {
            string id = Request.QueryString["workflowDefId"];
            if (id == null)
                throw new ArgumentNullException("workflowDefId");
            else
                return new Guid(id);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ClearErrorMessage();
        if (!IsPostBack)
        {
            _presenter.OnViewLoaded(Helpers.TenantAlias);
        }        
    }

    #region RowDataBound

    protected void ProcessStepsGridView_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            BindRow(e.Row);
        }
    }

    private void BindRow(GridViewRow row)
    {
        WorkflowStep step = (WorkflowStep)row.DataItem;
        FillTypes(row);
        SelectType(step, row);
        FillRoles(row);
        SelectRole(step, row);
        UpdateStepImage(row);
    }

    private void FillTypes(GridViewRow row)
    {
        DropDownList list = row.FindControl("TypeDropDown") as DropDownList;
        if (list != null)
        {
            list.DataTextField = "Value";
            list.DataValueField = "Key";
            list.DataSource = this.StepTypes;
            list.DataBind();
        }
    }

    private void SelectType(WorkflowStep step, GridViewRow row)
    {
        string type = step.Type;
        if (type != null)
        {
            DropDownList list = row.FindControl("TypeDropDown") as DropDownList;
            list.SelectedValue = type;
        }
    }

    private void FillRoles(GridViewRow row)
    {
        DropDownList list = row.FindControl("RoleDropDown") as DropDownList;
        if (list != null)
        {
            list.DataSource = this.Roles;
            list.DataBind();
        }
    }

    private void SelectRole(WorkflowStep step, GridViewRow row)
    {
        string role = ((WorkflowStep)row.DataItem).Role;
        if (role != null)
        {
            DropDownList list = row.FindControl("RoleDropDown") as DropDownList;
            list.SelectedValue = role;
        }
    }

    #endregion

    public void ShowSteps()
    {
        ProcessStepsGridView.DataSource = this.Steps;
        ProcessStepsGridView.DataBind();
    }

    protected void AddButton_Click(object sender, EventArgs e)
    {
        _presenter.OnAddStep();
    }

    public void UpdateSteps()
    {
        Steps.Clear();
        foreach (GridViewRow row in ProcessStepsGridView.Rows)
        {
            TextBox nameTextBox = row.FindControl("NameTextBox") as TextBox;
            DropDownList typeDropDown = row.FindControl("TypeDropDown") as DropDownList;
            DropDownList roleDropDown = row.FindControl("RoleDropDown") as DropDownList;
            Steps.Add(new WorkflowStep(nameTextBox.Text, typeDropDown.SelectedValue, roleDropDown.SelectedValue));
            UpdateStepImage(row);
        }
    }

    protected void SaveButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            _presenter.OnSaveWorkflow();
        }
    }

    protected void CancelButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }

    protected void ProcessStepsGridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index = Convert.ToInt32(e.CommandArgument);
        UpdateSteps();

        switch (e.CommandName)
        {
            case "deleteStep":
                _presenter.OnRemoveStep(index);
                break;
            case "moveUpStep":
                _presenter.OnMoveStepUp(index);
                break;
            case "moveDownStep":
                _presenter.OnMoveStepDown(index);
                break;

            default:
                break;
        }
    }

    protected void ProcessStepsGridView_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string rowIndex = e.Row.RowIndex.ToString();
            LinkButton deleteButton = e.Row.FindControl("ImageButtonDelete") as LinkButton;
            if (deleteButton != null)
            {
                deleteButton.CommandArgument = rowIndex;
            }
            LinkButton moveUpButton = e.Row.FindControl("ImageButtonMoveUp") as LinkButton;
            if (moveUpButton != null)
            {
                moveUpButton.CommandArgument = rowIndex;
            }
            LinkButton moveDownButton = e.Row.FindControl("ImageButtonMoveDown") as LinkButton;
            if (moveDownButton != null)
            {
                moveDownButton.CommandArgument = rowIndex;
            }
        }
    }

    protected void TypeDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        UpdateSteps();
    }

    public void UpdateStepImage(GridViewRow row)
    {
        DropDownList typeDropDown = row.FindControl("TypeDropDown") as DropDownList;
        Image stepImage = row.FindControl("ImgStep") as Image;
        Array arr = typeDropDown.SelectedValue.Split('.');
        string stepTypeName = (string)arr.GetValue(arr.Length - 1);
        stepImage.ImageUrl = string.Format(Resources.ActivityImageUrl, stepTypeName);
    }

    public void ShowErrorMessage(string errorMessage)
    {
        ErrorMessageLabel.Text = errorMessage;
    }

    public void ClearErrorMessage()
    {
        ShowErrorMessage(string.Empty);
    }

    public List<string> Roles
    {
        set { ViewState["Roles"] = value; }
        get { return ViewState["Roles"] as List<string>; }
    }

    public Dictionary<string, string> StepTypes
    {
        set { ViewState["StepTypes"] = value; }
        get { return ViewState["StepTypes"] as Dictionary<string, string>; }
    }
}
